﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;

namespace YXShop.TemplateAction
{
    /// <summary>
    /// 标签参数
    /// </summary>
    public struct LabelParameter
    {
        /// <summary>
        /// 参数名称
        /// </summary>
        public string LPName;
        /// <summary>
        /// 参数值
        /// </summary>
        public string LPValue;
    }
    public class Template
    {

        /// <summary>
        /// 模型名称
        /// </summary>
        protected string _modelname;
        /// <summary>
        /// 模板的物理路径
        /// </summary>
        protected string _temppath;
        /// <summary>
        /// 模板的文件内容
        /// </summary>
        protected string _tempcontent = string.Empty;
        /// <summary>
        /// 是否编辑标签
        /// </summary>
        protected static bool _whethereidtLable = false;
        /// <summary>
        /// 模板的最终的内容
        /// </summary>
        protected string _tempfinallyconent = string.Empty;
        /// <summary>
        /// 标签名称
        /// </summary>
        protected string _LabelName = string.Empty;
        /// <summary>
        /// 标签种类
        /// </summary>
        protected string _LabelType = string.Empty;
        /// <summary>
        /// 最终的HTML代码
        /// </summary>
        protected string _FinalHtmlCode = string.Empty;

        /// <summary>
        /// 模板文件名
        /// </summary>
        protected static string _templatefilename = string.Empty;

        /// <summary>
        /// 模板路径
        /// </summary>
        protected static string _templatepath = string.Empty;

        public void BackPath(string filename, string path)
        {
            _templatefilename = filename;
            _templatepath = path;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="labelname">标签名称</param>
        public Template(string labelname, string labeltype)
        {
            _LabelName = labelname;
            _LabelType = labeltype;
        }
        /// <summary>
        /// 标签名称
        /// </summary>
        public string LabelName
        {
            get { return _LabelName; }
        }
        /// <summary>
        /// 标签种类
        /// </summary>
        public string LabelType
        {
            get { return _LabelType; }
        }
        /// <summary> 
        /// 转换模板所有的标签(前台)
        /// </summary>
        public void FrontReplaceLabels()
        {
            string pattern = @"\[YX:unLoop,[^\]]+\][\s\S]*?\[/YX:unLoop\]|\[YX:Loop,[^\]]+\][\s\S]*?\[/YX:Loop\]";
            _tempfinallyconent = _tempcontent;
            StringBuilder GetTemp = new StringBuilder();
            MatchCollection macths = Regex.Matches(_tempfinallyconent, pattern);
            foreach (Match macth in macths)
            {
                string temptag = "";
                temptag = macth.ToString();
                if (temptag.ToString() != null)
                {
                    Template theLabel = null;
                    StringBuilder joinstr = new StringBuilder();
                    String strFinalHtmlCode = string.Empty;
                    theLabel = Template.GetLabel("dd", "d");
                    theLabel.SetLabelContent(temptag);
                    theLabel.MakeHtmlCode();
                    joinstr.Append(theLabel.FinalHtmlCode);
                    strFinalHtmlCode = joinstr.ToString();
                    _tempfinallyconent = _tempfinallyconent.Replace(temptag.Trim(), strFinalHtmlCode);
                    GetTemp = GetTemp.Replace(temptag, FinallyContent);

                }
            }
            MatchCollection repeat_macths = Regex.Matches(_tempfinallyconent, pattern);
            foreach (Match macth in repeat_macths)
            {
                _tempcontent = _tempfinallyconent;
                FrontReplaceLabels();
            }
        }
        /// <summary> 
        /// 转换模板所有的标签
        /// </summary>
        public void ReplaceLabels()
        {
            string pattern = @"{#[\s\S]*?#}";
            _tempfinallyconent = _tempcontent;
            StringBuilder GetTemp = new StringBuilder();
            MatchCollection macths = Regex.Matches(_tempfinallyconent, pattern);
            foreach (Match macth in macths)
            {
                string temptag = "";
                temptag = macth.ToString();
                int templength = temptag.ToString().IndexOf("{#") + 2;
                int templength2 = temptag.ToString().IndexOf("#}");
                if (temptag.ToString().Substring(templength, templength2 - templength).ToString() != null && temptag.IndexOf("*") > -1)
                {
                    string Str_Tag = temptag.ToString().Substring(templength, templength2 - templength);//找到标签
                    string[] tempString = Str_Tag.Split('*');
                    string Tag_Name = tempString[0].ToString();//获得标签名称,在之后做调用前的比较。
                    string Tag_ID = tempString[1].ToString();//获取标签的参数
                    string[] tempid = GetTagID(Tag_ID);//获取标签的参数列表并进行拆分
                    Template theLabel = null;
                    StringBuilder joinstr = new StringBuilder();
                    String strFinalHtmlCode = string.Empty;
                    switch (Tag_Name)
                    {
                        case "YXShopDefinTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            theLabel.GetContentFromDB();
                            theLabel.MakeHtmlCode();
                            joinstr.Append(LableEdi(Tag_Name, Convert.ToString(tempid[0])));
                            joinstr.Append(theLabel.FinalHtmlCode);
                            strFinalHtmlCode = joinstr.ToString();
                            _tempfinallyconent = _tempfinallyconent.Replace(temptag.Trim(), strFinalHtmlCode);
                            GetTemp = GetTemp.Replace(temptag, FinallyContent);
                            break;
                        case "YXShopRivetTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            theLabel.GetContentFromDB();
                            theLabel.MakeHtmlCode();
                            joinstr.Append(LableEdi(Tag_Name, Convert.ToString(tempid[0])));
                            joinstr.Append(theLabel.FinalHtmlCode);
                            strFinalHtmlCode = joinstr.ToString();
                            _tempfinallyconent = _tempfinallyconent.Replace(temptag.Trim(), strFinalHtmlCode);
                            GetTemp = GetTemp.Replace(temptag, FinallyContent);
                            break;
                        case "YXShopFreeTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            theLabel.GetContentFromDB();
                            theLabel.MakeHtmlCode();
                            joinstr.Append(LableEdi(Tag_Name, Convert.ToString(tempid[0])));
                            joinstr.Append(theLabel.FinalHtmlCode);
                            strFinalHtmlCode = joinstr.ToString();
                            _tempfinallyconent = _tempfinallyconent.Replace(temptag.Trim(), strFinalHtmlCode);
                            GetTemp = GetTemp.Replace(temptag, FinallyContent);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        #region 传模板内容转换标签中所有的标签
        /// <summary>
        /// 转换标签中所有的标签
        /// </summary>
        /// <param name="LabelContent">标签内容</param>
        /// <returns></returns>
        public static string ReplaceLabels(string LabelContent)
        {
            string pattern = @"{#[\s\S]*?#}";
            string Labelfinallyconent = LabelContent;
            StringBuilder GetTemp = new StringBuilder();
            MatchCollection macths = Regex.Matches(Labelfinallyconent, pattern);
            foreach (Match macth in macths)
            {
                string temptag = "";
                temptag = macth.ToString();
                int templength = temptag.ToString().IndexOf("{#") + 2;
                int templength2 = temptag.ToString().IndexOf("#}");
                if (temptag.ToString().Substring(templength, templength2 - templength).ToString() != null && temptag.IndexOf("*") != -1)
                {
                    string Str_Tag = temptag.ToString().Substring(templength, templength2 - templength);//找到标签
                    string[] tempString = Str_Tag.Split('*');
                    string Tag_Name = tempString[0].ToString();  //获得标签名称,在之后做调用前的比较。
                    string Tag_ID = tempString[1].ToString();//获取标签的参数
                    string[] tempid = GetTagID(Tag_ID);//获取标签的参数列表并进行拆分
                    Template theLabel = null;
                    StringBuilder joinstr = new StringBuilder();
                    string strFinalHtmlCode = string.Empty;
                    switch (Tag_Name)
                    {
                        case "YXShopDefinTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            theLabel.GetContentFromDB();
                            theLabel.MakeHtmlCode();
                            joinstr = new StringBuilder();
                            joinstr.Append(LableEdi(Tag_Name, Convert.ToString(tempid[0])));
                            joinstr.Append(theLabel.FinalHtmlCode);
                            strFinalHtmlCode = joinstr.ToString();
                            Labelfinallyconent = Labelfinallyconent.Replace(temptag.Trim(), strFinalHtmlCode);
                            break;
                        case "YXShopRivetTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            theLabel.GetContentFromDB();
                            theLabel.MakeHtmlCode();
                            joinstr = new StringBuilder();
                            joinstr.Append(LableEdi(Tag_Name, Convert.ToString(tempid[0])));
                            joinstr.Append(theLabel.FinalHtmlCode);
                            strFinalHtmlCode = joinstr.ToString();
                            Labelfinallyconent = Labelfinallyconent.Replace(temptag.Trim(), strFinalHtmlCode);
                            break;
                        case "YXShopFreeTag":
                            theLabel = Template.GetLabel(Convert.ToString(tempid[0]), Tag_Name);
                            theLabel.GetContentFromDB();
                            theLabel.MakeHtmlCode();
                            joinstr = new StringBuilder();
                            joinstr.Append(LableEdi(Tag_Name, Convert.ToString(tempid[0])));
                            joinstr.Append(theLabel.FinalHtmlCode);
                            strFinalHtmlCode = joinstr.ToString();
                            Labelfinallyconent = Labelfinallyconent.Replace(temptag.Trim(), strFinalHtmlCode);
                            break;
                        default:
                            break;
                    }
                }
            }
            return Labelfinallyconent;
        }
        #endregion

        #region 模板页编辑标签图标
        /// <summary>
        /// 模板页编辑标签图标
        /// </summary>
        /// <param name="LableType"></param>
        /// <param name="LableName"></param>
        /// <returns></returns>
        public static string LableEdi(string LableType, string LableName)
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            StringBuilder str = new StringBuilder();
            if (_whethereidtLable)
            {
                switch (LableType)
                {
                    case "YXShopDefinTag":
                        str.Append("<div id=\"listpic\" style=\"width:50px;height:30px;position:absolute;z-index:2;border:#ff0000 solid 1.5px;background-color: #0AB801;filter:Alpha(Opacity=50);\" onmouseover=\"showlabel(this,'over','article','')\" onmouseout=\"showlabel(this,'out','article','')\" onclick=\"showlabeltype(this,'click','" + LableType + "','" + LableName.Trim() + "','" + _templatefilename.Trim() + "','" + _templatepath + "','" + ChangeHope.WebPage.PageRequest.GetQueryString("styleId") + "')\"><div style='position:absolute;z-index:6;' onclick='return false;'  onmouseover=\"ckjump(0)\" onmouseout=\"ckjump(1)\"><img src=\"" + sp.DummyPaht + "admin/images/position.jpg\"  style='width:21px;height:21px;' border=\"0\" usemap=\"#Maplistpic\"  />");

                        str.Append("<map name=\"Maplistpic\"><area shape=\"rect\" coords=\"7,0,14,7\" href=\"javascript:\"  onMouseDown=\"change_po('up',1,'listpic');\"  onMouseUp=\"change_po('up',0,'listpic')\"  alt=\"向上\" />");
                        str.Append("<area shape=\"rect\" coords=\"7,14,14,21\" href=\"javascript:\"  onMouseDown=\"change_po('down',1,'listpic')\" onMouseUp=\"change_po('down',0,'listpic');\"  alt=\"向下\" />");
                        str.Append("<area shape=\"rect\" coords=\"0,7,7,14\" href=\"javascript:\"  onMouseDown=\"change_po('left',1,'listpic')\"  onMouseUp=\"change_po('left',0,'listpic');\"   alt=\"向左\" />");
                        str.Append("<area shape=\"rect\" coords=\"14,7,21,14\" href=\"javascript:\" onMouseDown=\"change_po('right',1,'listpic')\" onMouseUp=\"change_po('right',0,'listpic');\"  alt=\"向右\" /></map>");
                        str.Append("</div></div>");
                        break;
                    case "YXShopFreeTag":
                        YXShop.BLL.Templates.FreeLabel fb = new YXShop.BLL.Templates.FreeLabel();
                        List<YXShop.Model.Templates.FreeLabel> flb = fb.GetListByWhere(" free_name= '"+LableName+"'");
                        if (flb.Count > 0)
                        {
                            //从模版修改
                            str.Append("<div id=\"listpic\" style=\"width:50px;height:30px;position:absolute;z-index:2;border:#ff0000 solid 1.5px;background-color: #0AB801;filter:Alpha(Opacity=50);\" onmouseover=\"showlabel(this,'over','article','');\" onmouseout=\"showlabel(this,'out','article','');\" onclick=\"showFreelabel(this,'click','" + flb[0].Id + "');\"><div style='position:absolute;z-index:6;' onclick='return false;'  onmouseover=\"ckjump(0);\" onmouseout=\"ckjump(1);\"><img src=\"" +sp.DummyPaht + "admin/images/position.jpg\"  style='width:21px;height:21px;' border=\"0\" usemap=\"#Maplistpic\"  />");
                            str.Append("<map name=\"Maplistpic\"><area shape=\"rect\" coords=\"7,0,14,7\" href=\"javascript:\"  onMouseDown=\"change_po('up',1,'listpic');\"  onMouseUp=\"change_po('up',0,'listpic');\"  alt=\"向上\" />");
                            str.Append("<area shape=\"rect\" coords=\"7,14,14,21\" href=\"javascript:\"  onMouseDown=\"change_po('down',1,'listpic');\" onMouseUp=\"change_po('down',0,'listpic');\"  alt=\"向下\" />");
                            str.Append("<area shape=\"rect\" coords=\"0,7,7,14\" href=\"javascript:\"  onMouseDown=\"change_po('left',1,'listpic');\"  onMouseUp=\"change_po('left',0,'listpic');\"   alt=\"向左\" />");
                            str.Append("<area shape=\"rect\" coords=\"14,7,21,14\" href=\"javascript:\" onMouseDown=\"change_po('right',1,'listpic');\" onMouseUp=\"change_po('right',0,'listpic');\"  alt=\"向右\" />");
                            str.Append("</map></div></div>");

                        }
                        else
                        {   //从模版添加
                            str.Append("<div id=\"listpic\" style=\"width:50px;height:30px;position:absolute;z-index:2;border:#ff0000 solid 1.5px;background-color: #0AB801;filter:Alpha(Opacity=50);\" onmouseover=\"showlabel(this,'over','article','');\" onmouseout=\"showlabel(this,'out','article','');\" onclick=\"showlabeltype(this,'click','" + LableType + "','" + LableName + "','" + _templatefilename + "','" + _templatepath + "','" + ChangeHope.WebPage.PageRequest.GetQueryString("styleId") + "');\"><div style='position:absolute;z-index:6;' onclick='return false;'  onmouseover=\"ckjump(0);\" onmouseout=\"ckjump(1);\"><img src=\"" + sp.DummyPaht + "admin/images/position.jpg\"  style='width:21px;height:21px;' border=\"0\" usemap=\"#Maplistpic\"  />");
                            str.Append("<map name=\"Maplistpic\"><area shape=\"rect\" coords=\"7,0,14,7\" href=\"javascript:\"  onMouseDown=\"change_po('up',1,'listpic');\"  onMouseUp=\"change_po('up',0,'listpic');\"  alt=\"向上\" />");
                            str.Append("<area shape=\"rect\" coords=\"7,14,14,21\" href=\"javascript:\"  onMouseDown=\"change_po('down',1,'listpic');\" onMouseUp=\"change_po('down',0,'listpic');\"  alt=\"向下\" />");
                            str.Append("<area shape=\"rect\" coords=\"0,7,7,14\" href=\"javascript:\"  onMouseDown=\"change_po('left',1,'listpic');\"  onMouseUp=\"change_po('left',0,'listpic');\"   alt=\"向左\" />");
                            str.Append("<area shape=\"rect\" coords=\"14,7,21,14\" href=\"javascript:\" onMouseDown=\"change_po('right',1,'listpic');\" onMouseUp=\"change_po('right',0,'listpic');\"  alt=\"向右\" />");
                            str.Append("</map></div></div>");

                        }
                        break;

                    default:
                        break;
                }
            }
            return str.ToString();
        }
        #endregion

        /// <summary>
        /// 解析标签种类并返回标签实例
        /// </summary>
        /// <returns>跟距标签类型返回标签实例</returns>
        public static Template GetLabel(string labelname, string labelType)
        {
            Template reValue = null;
            string _labelname = labelname.ToUpper();
            if (Regex.Match(labelType, @"YXShopDefinTag", RegexOptions.Compiled).Success)
            {
                reValue = new CustomLabel(labelname, "1");
            }
            else if (Regex.Match(labelType, @"YXShopFreeTag", RegexOptions.Compiled).Success)
            {
                reValue = new FreeLabel(labelname, "3");
            }
            else if (Regex.Match(labelType, @"YXShopRivetTag", RegexOptions.Compiled).Success)
            {
                reValue = new CustomLabel(labelname, "2");
            }
            else
            {
                reValue = new CustomLabel(labelname, labelType);
            }
            return reValue;
        }
        #region 返回标签参数的字符串数组
        /// <summary>
        /// 返回标签参数的字符串数组
        /// </summary>
        /// <param name="stemp">标签的参数列表</param>
        /// <returns></returns>
        public static string[] GetTagID(string stemp)
        {
            string[] temp = null;
            try
            {
                if (stemp != "")
                {
                    temp = stemp.Split(',');
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return temp;
        }
        #endregion
        /// <summary>
        /// 构造函数
        /// </summary> 
        /// <param name="temppath">模板物理路径</param>
        public Template(string temppath)
        {
            _temppath = temppath;
        }
        /// <summary>
        /// 从数据库取得标签的内容
        /// </summary>
        /// <param name="cn"></param>
        public virtual void GetContentFromDB()
        {
        }
        /// <summary>
        /// 从数据库取得标签内容
        /// </summary>
        /// <returns></returns>
        public virtual string GetLabelContent()
        {
            return string.Empty;
        }
        /// <summary>
        /// 生成最终的HTML代码
        /// </summary>
        /// <param name="cn"></param>
        public virtual void MakeHtmlCode()
        {

        }
        public virtual void SetLabelContent(string labelContent)
        {
 
        }
        /// <summary>
        /// 读取模板的内容到变量
        /// </summary>
        public void GetHTML()
        {
            _tempcontent = ChangeHope.Common.FileHelper.ReadHtml(_temppath);
        }
        /// <summary>
        /// 是否编标签
        /// </summary>
        public void GetEidtLable(bool ft)
        {
            _whethereidtLable = ft;
        }
        /// <summary>
        /// 最终的标签HTML代码
        /// </summary>
        public string FinalHtmlCode
        {
            get
            {
                if (!string.IsNullOrEmpty(_FinalHtmlCode))
                {
                    return _FinalHtmlCode;
                }
                else
                {
                    if (_whethereidtLable)
                    {
                        return "内容暂无";
                    }
                    else
                    {
                        return "";
                    }
                }
            }
        }


        /// <summary>
        /// 获取模板转换标签后的内容
        /// </summary>
        public string FinallyContent
        {
            get { return _tempfinallyconent; }
            set { _tempfinallyconent = value; }
        }
        /// <summary>
        /// 是否编辑标签
        /// </summary>
        public bool WhethereidtLable
        {
            get { return _whethereidtLable; }
        }
        /// <summary>
        /// 获取模板的路径
        /// </summary>
        public string TempFilePath
        {
            get { return _temppath; }
        }
        /// <summary>
        /// 获取模板的内容
        /// </summary>
        public string OriginalContent
        {
            get { return _tempcontent; }
        }
        /**
         * 自由标签执行Sql返回集合
         *
         * 
         */
        protected DataTable _FinalDateTable;
        public DataTable FinalDateTable
        {
            get
            {
                return _FinalDateTable;
            }
            set
            {
                _FinalDateTable = value;
            }
        }


    }
}